package com.xz.Utils;

import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhangh     
 * @version V1.0.0
 * @projectName laob_special
 * @title     MyStrignUtils   
 * @package    com.laob.laob_special.util.custom  
 * @date   2019/9/24 11:39  
 * @explain
 */
public class MyStrignUtils {

    private MyStrignUtils myStrignUtils = null;

    private MyStrignUtils() {
    }

    public MyStrignUtils getMyStrignUtils() {
        if (myStrignUtils == null){
            myStrignUtils = new MyStrignUtils();
        }
        return myStrignUtils;
    }


    /**
     * 将请求头字符串封装为Map集合
     * @param headers
     * @return
     */
    public static Map<String,String> parseHeader(String headers){

        Map<String,String> headersMap = new HashMap<>();
        if (StringUtils.isEmpty(headers)){
            return null;
        }else {
            // 以:分割,得到所有header
            String[] split = headers.split("\n");
            // 遍历,得到每一个header的name和value
            for (String s : split) {
                // 以:分割成两个,第一个为name,第二个为value
                String[] header = s.split(":",2);
                if (header.length >= 2){
                    headersMap.put(header[0],header[1]);
                }
            }
        }
        return headersMap;
    }

    /**
     * Base64加密字符串
     * @param str
     * @return
     */
    public static String base64Encode(String str){
        if (str == null){
            return null;
        }
        String encode = new BASE64Encoder().encode(str.getBytes());
        return encode;
    }


    /**
     * Base64解密字符串
     * @param str
     * @return
     */
    public static String base64Decode(String str){
        String deCodedStr = null;
        try {
            if (str == null){
                return null;
            }
            byte[] bytes = new BASE64Decoder().decodeBuffer(str);
            deCodedStr = new String(bytes);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return deCodedStr;
    }


    //public static void main(String[] args) throws IOException {
    //    String str = "system(\"net user\");";
    //
    //    System.out.println(base64Encode(str));
    //}

}
